<?php
if (!defined('ABSPATH')) { exit; }

// 获取安全模块实例检查许可证状态
$security = wp_spider_premium_security();
$is_premium = $security->is_premium_activated();
?>

<div class="spa-container">
    <!-- 侧边导航栏 -->
    <nav class="spider-nav-sidebar">
        <div class="spider-nav-header">
            <h1 class="spider-nav-title">广告管理</h1>
        </div>
        
        <ul class="spider-nav-menu">
            <li class="spider-nav-item">
                <a href="#ads-list" class="spider-nav-link active" data-route="ads-list">
                    <span class="nav-icon">📋</span>
                    广告列表
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#ads-stats" class="spider-nav-link" data-route="ads-stats">
                    <span class="nav-icon">📊</span>
                    点击统计
                </a>
            </li>
            <li class="spider-nav-item">
                <a href="#ads-settings" class="spider-nav-link" data-route="ads-settings">
                    <span class="nav-icon">⚙️</span>
                    广告设置
                </a>
            </li>
        </ul>
        
        <!-- 广告位区域 -->
        <div class="spider-nav-ads" id="spider-nav-ads">
            <!-- 广告位将通过API动态加载 -->
        </div>
    </nav>
    
    <!-- 主内容区域 -->
    <main class="spider-content-area" id="spider-content-area">
        <div class="ad-management-content">
            <h2>广告管理</h2>
            <p>管理侧边栏广告位和查看点击统计。</p>
            
            <div class="ad-management-tabs">
                <button class="tab-button active" data-tab="ads-list">广告列表</button>
                <button class="tab-button" data-tab="ads-stats">点击统计</button>
                <button class="tab-button" data-tab="ads-settings">广告设置</button>
            </div>
            
            <div class="tab-content">
                <div id="ads-list" class="tab-panel active">
                    <h3>当前广告</h3>
                    <div id="ads-list-content">
                        <p>加载中...</p>
                    </div>
                </div>
                
                <div id="ads-stats" class="tab-panel">
                    <h3>点击统计</h3>
                    <div id="ads-stats-content">
                        <p>加载中...</p>
                    </div>
                </div>
                
                <div id="ads-settings" class="tab-panel">
                    <h3>广告设置</h3>
                    <div id="ads-settings-content">
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 页面底部标志 -->
<footer class="spider-footer">
    <div class="spider-footer-content">
        <a href="https://zibovip.top" target="_blank" class="spider-footer-logo">
            <span class="logo-text">小Z</span>
        </a>
    </div>
</footer>

<style>
.ad-management-content {
    padding: 20px;
}

.ad-management-tabs {
    display: flex;
    border-bottom: 1px solid #ddd;
    margin-bottom: 20px;
}

.tab-button {
    padding: 10px 20px;
    border: none;
    background: none;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    transition: all 0.3s ease;
}

.tab-button.active {
    border-bottom-color: #0073aa;
    color: #0073aa;
    font-weight: 600;
}

.tab-button:hover {
    background: #f5f5f5;
}

.tab-panel {
    display: none;
}

.tab-panel.active {
    display: block;
}

.ad-item-management {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.ad-item-management img {
    width: 80px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
}

.ad-item-info {
    flex: 1;
}

.ad-item-info h4 {
    margin: 0 0 5px 0;
    color: #333;
}

.ad-item-info p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.ad-item-actions {
    display: flex;
    gap: 10px;
}

.btn {
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.3s ease;
}

.btn-primary {
    background: #0073aa;
    color: white;
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn:hover {
    opacity: 0.8;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.stat-card {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
}

.stat-card h3 {
    margin: 0 0 10px 0;
    color: #0073aa;
    font-size: 24px;
}

.stat-card p {
    margin: 0;
    color: #666;
}
</style>

<script>
jQuery(document).ready(function($) {
    'use strict';
    
    // 确保ajaxurl变量存在
    if (typeof ajaxurl === 'undefined') {
        window.ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    }
    
    // 标签页切换
    $('.tab-button').on('click', function() {
        const tabId = $(this).data('tab');
        
        // 更新按钮状态
        $('.tab-button').removeClass('active');
        $(this).addClass('active');
        
        // 更新面板显示
        $('.tab-panel').removeClass('active');
        $('#' + tabId).addClass('active');
        
        // 加载对应内容
        loadTabContent(tabId);
    });
    
    // 加载标签页内容
    function loadTabContent(tabId) {
        switch(tabId) {
            case 'ads-list':
                loadAdsList();
                break;
            case 'ads-stats':
                loadAdsStats();
                break;
            case 'ads-settings':
                loadAdsSettings();
                break;
        }
    }
    
    // 加载广告列表
    function loadAdsList() {
        const container = $('#ads-list-content');
        container.html('<p>加载中...</p>');
        
        $.post(ajaxurl, {
            action: 'spider_get_ads_data',
            nonce: wpSpiderMonitor.nonce
        })
        .done(function(response) {
            if (response.success && response.data) {
                renderAdsList(response.data);
            } else {
                container.html('<p>加载广告列表失败</p>');
            }
        })
        .fail(function() {
            container.html('<p>网络错误，请重试</p>');
        });
    }
    
    // 渲染广告列表
    function renderAdsList(ads) {
        const container = $('#ads-list-content');
        
        if (ads.length === 0) {
            container.html('<p>暂无广告</p>');
            return;
        }
        
        let html = '';
        ads.forEach(ad => {
            html += `
                <div class="ad-item-management">
                    <img src="${ad.image}" alt="${ad.title}" onerror="this.src='https://via.placeholder.com/80x40/666666/ffffff?text=广告'">
                    <div class="ad-item-info">
                        <h4>${ad.title}</h4>
                        <p>${ad.description}</p>
                        <p><strong>链接:</strong> ${ad.link}</p>
                        <p><strong>状态:</strong> ${ad.active ? '活跃' : '停用'}</p>
                    </div>
                    <div class="ad-item-actions">
                        <button class="btn btn-primary" onclick="editAd('${ad.id}')">编辑</button>
                        <button class="btn btn-danger" onclick="deleteAd('${ad.id}')">删除</button>
                    </div>
                </div>
            `;
        });
        
        container.html(html);
    }
    
    // 加载广告统计
    function loadAdsStats() {
        const container = $('#ads-stats-content');
        container.html('<p>加载中...</p>');
        
        // 模拟统计数据
        setTimeout(() => {
            container.html(`
                <div class="stats-grid">
                    <div class="stat-card">
                        <h3>1,234</h3>
                        <p>总点击次数</p>
                    </div>
                    <div class="stat-card">
                        <h3>5.6%</h3>
                        <p>点击率</p>
                    </div>
                    <div class="stat-card">
                        <h3>89</h3>
                        <p>今日点击</p>
                    </div>
                    <div class="stat-card">
                        <h3>2</h3>
                        <p>活跃广告</p>
                    </div>
                </div>
                <p><em>注：统计数据为示例数据，实际应用中需要从数据库获取</em></p>
            `);
        }, 500);
    }
    
    // 加载广告设置
    function loadAdsSettings() {
        const container = $('#ads-settings-content');
        container.html(`
            <div class="ad-settings-form">
                <h4>广告显示设置</h4>
                <p>
                    <label>
                        <input type="checkbox" checked> 在侧边栏显示广告
                    </label>
                </p>
                <p>
                    <label>
                        <input type="checkbox" checked> 启用点击统计
                    </label>
                </p>
                <p>
                    <label>
                        广告刷新间隔: 
                        <select>
                            <option value="300">5分钟</option>
                            <option value="600" selected>10分钟</option>
                            <option value="1800">30分钟</option>
                            <option value="3600">1小时</option>
                        </select>
                    </label>
                </p>
                <button class="btn btn-primary">保存设置</button>
            </div>
        `);
    }
    
    // 加载侧边栏广告
    loadSidebarAds();
    
    // 初始化加载第一个标签页
    loadTabContent('ads-list');
});

// 编辑广告
function editAd(adId) {
    alert('编辑广告功能: ' + adId);
}

// 删除广告
function deleteAd(adId) {
    if (confirm('确定要删除这个广告吗？')) {
        alert('删除广告功能: ' + adId);
    }
}

// 加载侧边栏广告位（复用之前的函数）
function loadSidebarAds() {
    const adsContainer = jQuery('#spider-nav-ads');
    if (adsContainer.length === 0) return;
    
    // 显示加载状态
    adsContainer.html('<div class="ad-loading">加载广告中...</div>');
    
    // 从API获取广告数据
    jQuery.post(ajaxurl, {
        action: 'spider_get_ads_data',
        nonce: wpSpiderMonitor.nonce
    })
    .done(function(response) {
        if (response.success && response.data) {
            renderAds(response.data);
        } else {
            // 如果API失败，显示默认广告
            renderDefaultAds();
        }
    })
    .fail(function() {
        console.warn('获取广告数据失败，显示默认广告');
        renderDefaultAds();
    });
    
    function renderAds(ads) {
        // 过滤活跃的广告
        const activeAds = ads.filter(ad => ad.active);
        
        if (activeAds.length === 0) {
            adsContainer.html('<div class="ad-no-content">暂无广告</div>');
            return;
        }
        
        // 渲染广告
        let adsHTML = '';
        activeAds.forEach(ad => {
            adsHTML += `
                <div class="ad-item" data-ad-id="${ad.id}">
                    <a href="${ad.link}" target="${ad.target}" style="text-decoration: none; color: inherit;">
                        <img src="${ad.image}" alt="${ad.title}" loading="lazy" onerror="this.src='https://via.placeholder.com/200x100/666666/ffffff?text=广告图片'">
                        <div class="ad-title">${ad.title}</div>
                        <div class="ad-desc">${ad.description}</div>
                    </a>
                </div>
            `;
        });
        
        adsContainer.html(adsHTML);
        bindAdClickEvents();
        console.log('侧边栏广告加载完成，共', activeAds.length, '个广告');
    }
    
    function renderDefaultAds() {
        // 默认广告数据
        const defaultAds = [
            {
                id: 'ad-default-1',
                title: 'WordPress优化服务',
                description: '专业WordPress网站优化',
                image: 'https://via.placeholder.com/200x100/0073aa/ffffff?text=WordPress+优化',
                link: 'https://zibovip.top',
                target: '_blank'
            },
            {
                id: 'ad-default-2', 
                title: 'SEO工具推荐',
                description: '提升网站搜索排名',
                image: 'https://via.placeholder.com/200x100/28a745/ffffff?text=SEO+工具',
                link: 'https://zibovip.top',
                target: '_blank'
            }
        ];
        
        renderAds(defaultAds);
    }
    
    function bindAdClickEvents() {
        // 添加广告点击统计
        adsContainer.off('click.ad-tracking').on('click.ad-tracking', '.ad-item a', function(e) {
            const adId = jQuery(this).closest('.ad-item').data('ad-id');
            console.log('广告点击:', adId);
            
            // 发送广告点击统计到服务器
            jQuery.post(ajaxurl, {
                action: 'spider_track_ad_click',
                ad_id: adId,
                nonce: wpSpiderMonitor.nonce
            }).fail(function() {
                console.warn('广告点击统计发送失败');
            });
        });
    }
}
</script>
